package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.Likes;
import com.recipedb.recipedb.entity.LikesId;
import com.recipedb.recipedb.service.LikesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/likes")
public class LikesController {

    @Autowired
    private LikesService service;

    @PostMapping
    public Likes add(@RequestBody Likes entity) {
        return service.save(entity);
    }

    @DeleteMapping
    public ResponseEntity<?> deleteLike(@RequestBody Map<String, Object> requestBody) {
        try {
            Long userId = Long.valueOf(requestBody.get("userId").toString());
            Long recipeId = Long.valueOf(requestBody.get("recipeId").toString());

            service.deleteByUserIdAndRecipeId(userId, recipeId);
            return ResponseEntity.ok().body("删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("不存在记录");
        }
    }

    @GetMapping("/single")
    public Optional<Likes> get(@RequestBody LikesId id) {
        return service.findById(id);
    }

    @GetMapping("/all")
    public List<Likes> getAll() {
        return service.findAll();
    }

    // 根据菜谱ID查询所有点赞记录
    @GetMapping("/by-recipe")
    public List<Likes> getLikesByRecipeId(@RequestParam Long recipeId) {
        return service.findByRecipeId(recipeId);
    }

}
